package com.ruoyi.tb.lmt.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.tb.lmt.domain.TbLmtrepairWorkdetail;
import com.ruoyi.tb.lmt.domain.bo.TbLmtrepairWorkdetailBo;
import com.ruoyi.tb.lmt.service.ITbLmtrepairWorkdetailService;
import com.ruoyi.tb.lmt.service.ITbRepairplanlistService;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tb.lmt.domain.vo.TbWorktemplateVo;
import com.ruoyi.tb.lmt.domain.bo.TbWorktemplateBo;
import com.ruoyi.tb.lmt.service.ITbWorktemplateService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 年修/定检内容
 *
 * @author ruoyi
 * @date 2023-11-30
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xha-lmt/worktemplate")
public class TbWorktemplateController extends BaseController {

    private final ITbWorktemplateService iTbWorktemplateService;

    private final ITbLmtrepairWorkdetailService tbLmtrepairWorkdetailService;

    private final ITbRepairplanlistService tbRepairplanlistService;

    /**
     * 查询年修/定检内容列表
     */
    //@SaCheckPermission("xha-lmt:worktemplate:list")
    @GetMapping("/list")
    public TableDataInfo<TbWorktemplateVo> list(TbWorktemplateBo bo, PageQuery pageQuery) {
        return iTbWorktemplateService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出年修/定检内容列表
     */
    @SaCheckPermission("xha-lmt:worktemplate:export")
    @Log(title = "年修/定检内容", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TbWorktemplateBo bo, HttpServletResponse response) {
        List<TbWorktemplateVo> list = iTbWorktemplateService.queryList(bo);
        ExcelUtil.exportExcel(list, "年修-定检内容", TbWorktemplateVo.class, response);
    }

    /**
     * 获取年修/定检内容详细信息
     *
     * @param ID 主键
     */
    @SaCheckPermission("xha-lmt:worktemplate:query")
    @GetMapping("/{ID}")
    public R<TbWorktemplateVo> getInfo(@NotNull(message = "主键不能为空")
                                       @PathVariable Long ID) {
        return R.ok(iTbWorktemplateService.queryById(ID));
    }

    /**
     * 新增年修/定检内容
     */
    @SaCheckPermission("xha-lmt:worktemplate:add")
    @Log(title = "年修/定检内容", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TbWorktemplateBo bo) {
        return toAjax(iTbWorktemplateService.insertByBo(bo));
    }

    /**
     * 修改年修/定检内容
     */
    @SaCheckPermission("xha-lmt:worktemplate:edit")
    @Log(title = "年修/定检内容", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TbWorktemplateBo bo) {
        TbLmtrepairWorkdetail workdetail = new TbLmtrepairWorkdetail();
        workdetail.setWorkType(bo.getRepairType());
        workdetail.setWorkCategoryId(bo.getWorkCategoryId());
        workdetail.setWorkKind(bo.getWorkKind());
        workdetail.setWorkCategory(bo.getWorkCategory());
        List<Long> repairIds = tbRepairplanlistService.selectIdsByType(bo.getLmtType(), bo.getRepairType());
        if(repairIds != null && repairIds.size() > 0) {
            workdetail.setFormConfig(bo.getFormConfig());
            tbLmtrepairWorkdetailService.updateByRepairIdsAndCategoryAndKind(workdetail, repairIds);
            workdetail.setPrintConfig(bo.getPrintConfig());
            tbLmtrepairWorkdetailService.updateByRepairIdsAndCategoryAndKind1(workdetail, repairIds);
        }
        //TODO 更新工作
        return toAjax(iTbWorktemplateService.updateByBo(bo));
    }

    /**
     * 删除年修/定检内容
     *
     * @param IDs 主键串
     */
    @SaCheckPermission("xha-lmt:worktemplate:remove")
    @Log(title = "年修/定检内容", businessType = BusinessType.DELETE)
    @DeleteMapping("/{IDs}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] IDs) {
        return toAjax(iTbWorktemplateService.deleteWithValidByIds(Arrays.asList(IDs), true));
    }

    @GetMapping("/formConfig")
    public R<String> formConfig(Long id) {
        return R.ok(iTbWorktemplateService.formConfig(id));
    }

    /**
     * 导入表格
     */
    @SaCheckPermission("xha-lmt:worktemplate:importExcel")
    @PostMapping(value = "/importExcel", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<List<TbWorktemplateVo>> importExcel(@RequestPart("file") MultipartFile file) throws Exception {
        // 处理解析结果
        ExcelResult<TbWorktemplateVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), TbWorktemplateVo.class, true);
        // 获取从 excelResult.getList() 中获取的 TbWorktemplateVo 列表
        List<TbWorktemplateVo> voList = excelResult.getList();

        // 找出 id 为 null 的子集合
        List<TbWorktemplateVo> idIsNullList = voList.stream()
            .filter(vo -> vo.getID() == null)
            .collect(Collectors.toList());

        // 找出 id 不为 null 但在 tb_worktemplate 表中不存在的子集合
        List<TbWorktemplateVo> idNotExistInDBList = voList.stream()
            .filter(vo -> vo.getID() != null)
            .filter(vo -> !iTbWorktemplateService.existsById(vo.getID()))
            .collect(Collectors.toList());

        // 结合两个子集合，形成新的集合
        List<TbWorktemplateVo> newVoList = new ArrayList<>();
        newVoList.addAll(idIsNullList);
        newVoList.addAll(idNotExistInDBList);

        // 更新操作：找出 id 存在于数据库中的子集合并执行更新操作
        List<TbWorktemplateVo> idExistInDBList = voList.stream()
            .filter(vo -> vo.getID() != null)
            .filter(vo -> iTbWorktemplateService.existsById(vo.getID()))
            .collect(Collectors.toList());

        // 更新数据库中已存在的数据
        for (TbWorktemplateVo vo : idExistInDBList) {
            // 创建一个新的 TbWorktemplateBo 对象
            TbWorktemplateBo bo = new TbWorktemplateBo();
            bo.setID(vo.getID()); // 设置ID，用于更新操作
            bo.setLmtType(vo.getLmtType());
            bo.setRepairTimes(vo.getRepairTimes());
            bo.setWorkCategory(vo.getWorkCategory());
            bo.setWorkCategoryId(vo.getWorkCategoryId());
            bo.setWorkHours(vo.getWorkHours());
            bo.setWorkKind(vo.getWorkKind());
            bo.setWorkMode(vo.getWorkMode());
            bo.setWorkName(vo.getWorkName());
            bo.setWorkRequire(vo.getWorkRequire());
            bo.setWorkUser1(vo.getWorkUser1());
            bo.setWorkUser2(vo.getWorkUser2());
            bo.setWorkUser3(vo.getWorkUser3());
            bo.setWorkGroup(vo.getWorkGroup());
            bo.setWorkGroup2(vo.getWorkGroup2());
            bo.setWorkGroup3(vo.getWorkGroup3());
            bo.setRemark(vo.getRemark());
            bo.setOrderNo(vo.getOrderNo());
            bo.setWorkDaySeq(vo.getWorkDaySeq());
            bo.setWorkDirectName(vo.getWorkDirectName());
            bo.setWorkDirectUrl(vo.getWorkDirectUrl());
            bo.setIszdf(vo.getIszdf());
            bo.setIsmustcheck(vo.getIsmustcheck());
            bo.setIsmustcheck2(vo.getIsmustcheck2());
            bo.setIsmustcheck3(vo.getIsmustcheck3());
            bo.setPreWorkIndex(vo.getPreWorkIndex());
            bo.setInspectionTopic(vo.getInspectionTopic());
            bo.setProductcodes(vo.getProductcodes());
            bo.setDataJson(vo.getDataJson());
            bo.setFormConfig(vo.getFormConfig());
            bo.setPrintConfig(vo.getPrintConfig());
            bo.setRepairType(vo.getRepairType());
            bo.setIsTestBed(vo.getIsTestBed());
            // 将转换后的 TbWorktemplateBo 对象添加到列表中
            iTbWorktemplateService.updateByBo(bo);
        }

        // 创建一个空的 TbWorktemplateBo 列表，用于存放转换后的对象
        List<TbWorktemplateBo> boList = new ArrayList<>();

        // 遍历 TbWorktemplateVo 列表，进行转换
        for (TbWorktemplateVo vo : newVoList) {
            // 创建一个新的 TbWorktemplateBo 对象
            TbWorktemplateBo bo = new TbWorktemplateBo();
            bo.setLmtType(vo.getLmtType());
            bo.setWorkCategory(vo.getWorkCategory());
            bo.setWorkCategoryId(vo.getWorkCategoryId());
            bo.setWorkKind(vo.getWorkKind());
            bo.setWorkName(vo.getWorkName());
            bo.setRepairType(vo.getRepairType());
            List<TbWorktemplateVo> tbWorktemplateVos = iTbWorktemplateService.queryList(bo);
            if (tbWorktemplateVos != null && tbWorktemplateVos.size() > 0) {
                System.out.println("跳过");
                TbWorktemplateBo bo1 = new TbWorktemplateBo();
                bo1.setID(tbWorktemplateVos.get(0).getID()); // 设置ID，用于更新操作
                bo1.setLmtType(vo.getLmtType());
                bo1.setRepairTimes(vo.getRepairTimes());
                bo1.setWorkCategory(vo.getWorkCategory());
                bo1.setWorkCategoryId(vo.getWorkCategoryId());
                bo1.setWorkHours(vo.getWorkHours());
                bo1.setWorkKind(vo.getWorkKind());
                bo1.setWorkMode(vo.getWorkMode());
                bo1.setWorkName(vo.getWorkName());
                bo1.setWorkRequire(vo.getWorkRequire());
                bo1.setWorkUser1(vo.getWorkUser1());
                bo1.setWorkUser2(vo.getWorkUser2());
                bo1.setWorkUser3(vo.getWorkUser3());
                bo1.setWorkGroup(vo.getWorkGroup());
                bo1.setWorkGroup2(vo.getWorkGroup2());
                bo1.setWorkGroup3(vo.getWorkGroup3());
                bo1.setRemark(vo.getRemark());
                bo1.setOrderNo(vo.getOrderNo());
                bo1.setWorkDaySeq(vo.getWorkDaySeq());
                bo1.setWorkDirectName(vo.getWorkDirectName());
                bo1.setWorkDirectUrl(vo.getWorkDirectUrl());
                bo1.setIszdf(vo.getIszdf());
                bo1.setIsmustcheck(vo.getIsmustcheck());
                bo1.setIsmustcheck2(vo.getIsmustcheck2());
                bo1.setIsmustcheck3(vo.getIsmustcheck3());
                bo1.setPreWorkIndex(vo.getPreWorkIndex());
                bo1.setInspectionTopic(vo.getInspectionTopic());
                bo1.setProductcodes(vo.getProductcodes());
                bo1.setDataJson(vo.getDataJson());
                bo1.setFormConfig(vo.getFormConfig());
                bo1.setPrintConfig(vo.getPrintConfig());
                bo1.setRepairType(vo.getRepairType());
                bo1.setIsTestBed(vo.getIsTestBed());
                // 将转换后的 TbWorktemplateBo 对象添加到列表中
                iTbWorktemplateService.updateByBo(bo1);
                continue;
            }
            bo.setWorkMode(vo.getWorkMode());
            bo.setRepairTimes(vo.getRepairTimes());
            bo.setWorkHours(vo.getWorkHours());
            bo.setWorkRequire(vo.getWorkRequire());
            bo.setWorkUser1(vo.getWorkUser1());
            bo.setWorkUser2(vo.getWorkUser2());
            bo.setWorkUser3(vo.getWorkUser3());
            bo.setWorkGroup(vo.getWorkGroup());
            bo.setWorkGroup2(vo.getWorkGroup2());
            bo.setWorkGroup3(vo.getWorkGroup3());
            bo.setRemark(vo.getRemark());
            bo.setOrderNo(vo.getOrderNo());
            bo.setWorkDaySeq(vo.getWorkDaySeq());
            bo.setWorkDirectName(vo.getWorkDirectName());
            bo.setWorkDirectUrl(vo.getWorkDirectUrl());
            bo.setIszdf(vo.getIszdf());
            bo.setIsmustcheck(vo.getIsmustcheck());
            bo.setIsmustcheck2(vo.getIsmustcheck2());
            bo.setIsmustcheck3(vo.getIsmustcheck3());
            bo.setPreWorkIndex(vo.getPreWorkIndex());
            bo.setInspectionTopic(vo.getInspectionTopic());
            bo.setProductcodes(vo.getProductcodes());
            bo.setDataJson(vo.getDataJson());
            bo.setFormConfig(vo.getFormConfig());
            bo.setPrintConfig(vo.getPrintConfig());
            bo.setIsTestBed(vo.getIsTestBed());
            // 将转换后的 TbWorktemplateBo 对象添加到列表中
            boList.add(bo);
        }

// 将转换后的 TbWorktemplateBo 对象列表插入到数据库中
        for (TbWorktemplateBo bo : boList) {
            iTbWorktemplateService.insertByBo(bo);
        }
        return R.ok();
    }


}
